import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router' // 新增路由导入

// 创建axios实例
const service = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  timeout: 10000
})

// 请求拦截器（添加JWT）
service.interceptors.request.use(config => {
  const token = localStorage.getItem('access_token')
  if (token) {
    config.headers.authorization = `Bearer ${token}`
  }
  return config
})

// 响应拦截器（统一错误处理）
service.interceptors.response.use(
  response => response.data,
  error => {
    const status = error.response?.status
    const message = error.response?.data?.msg || '请求异常'

    switch (status) {
      case 401:
        ElMessage.error('认证失效，请重新登录')
        localStorage.removeItem('access_token')
        break
      case 409:
        ElMessage.warning(message)
        break
      default:
        ElMessage.error(message)
    }

    return Promise.reject(error)
  }
)



export default service